<?php
/**
 * Core_Controllers_Autoloader
 * autolad all requires classes
 * @author Adrian Stolarski
 */
class Core_Controller_Autoloader {
    public function class_to_load($class_name){
		
		/**
		 * Parse out filename where class should be located.
		 * This supports names like 'Example_Model' as well as 'Example_Model'.
		 */
		
		list($fileToLoad, $functionalityAndFolder) = preg_split("/_/", strrev($class_name), 2);
		$functionalityAndFolder = strrev($functionalityAndFolder);
		$fileToLoad = strrev($fileToLoad);
		list($trier, $functionality) = preg_split("/_/", strrev($functionalityAndFolder), 2);
		$functionality = strrev($functionality);
		$trier = strrev($trier);
		
		/**
		 * select the folder where class should be located
		 * bassed on $trier
		 */
		switch(strtolower($trier)){
			case "model":
				$folder = "/models/";
				break;
			case "data":
				$folder = "/data/";
				break;
			case "library":
				$folder = "/libraries/";
				break;
			case "driver":
				$folder = "/libraries/drivers/";
				break;
                        case "controller":
                                $folder = "/controllers/";
                                break;
			default:
				echo '<meta http-equiv="Refresh" content="0;url='.$_SERVER['HTTP_REFERER'].'">';
		}
		
		/**
		 * compose the filename
		 */
		$file = "./" . strtolower($functionality)  . strtolower($folder) . strtolower($fileToLoad) . ".php";
		try {
			
			/**
			 * fetch file
			 */
			if(file_exists($file)){
				/**
				 * get file
				 */
				include_once "$file";
			}
			else {
				/**
				 * file does not exists!
				 */
				throw new Exception("File '$file' not found!");
				//echo '<meta http-equiv="Refresh" content="0;url='.SITE_ROOT.'errors/404.html">';
			}
		}
		
		catch(Exception $e){
			echo $e->getMessage();
		}
	}
}
